package cn.oowoo.jsr303.common.config;


import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Author: zhangbin
 * @Date: 2019/4/22 17:44
 * @Return
 * @Description:日期校验
 * 
 */
@Slf4j
public class DateValidator implements ConstraintValidator<ValidDate, String> {
    ValidDate.PatternEnum pattern;

    @Override
    public void initialize(ValidDate validDate) {
        this.pattern = validDate.pattern();
    }
    @Override
    public boolean isValid(String dateStr, ConstraintValidatorContext constraintValidatorContext) {
        if(dateStr == null || dateStr.trim().length()<=0){
            return true;
        }
        dateStr = dateStr.trim();
        try {
            if(pattern == ValidDate.PatternEnum.yyyy_MM_dd){
                LocalDate.parse(dateStr,DateTimeFormatter.ofPattern(pattern.getPattern()));
            }else if(pattern == ValidDate.PatternEnum.yyyy_MM_dd_HH_mm_ss){
                LocalDateTime.parse(dateStr,DateTimeFormatter.ofPattern(pattern.getPattern()));
            }
            return true;
        }catch (Exception e){
            log.error("日期转化错误，这可能并不是后端开发者的问题,请尝试传入{}格式的日期字符串:{value: {}}", pattern, dateStr, e);
            return false;
        }
    }

    public static void main(String[] args) {

        LocalDateTime localDateTime = LocalDateTime.now();

        //采用系统给定的格式转化
        DateTimeFormatter dtf1 = DateTimeFormatter.ISO_DATE;//只要日期
        String date1 = dtf1.format(localDateTime);
        System.out.println(date1);

        //自定义格式化
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String date2 = dtf2.format(localDateTime);
        System.out.println(date2);

        //将字符串的日期转化为日期对象
        LocalDateTime res = LocalDateTime.parse("2018-12-11 11:11:11",dtf2);//采用dtf2格式转化
        System.out.println(res);

        LocalDate date = LocalDate.parse("2018-04-05",DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        System.out.println("格式化之后的日期=" + date);

    }
}
